package com.woniuxy.business.config;

import com.rabbitmq.client.Channel;
import com.woniuxy.business.util.WebSocketUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.io.IOException;

@Component
public class KillConsumer {
    @Resource
    private RedisTemplate<String,Integer> redisTemplate;
    @Resource
    private SqlProducer sqlProducer;

    @RabbitListener(queues = "kill_queue")
    public void receive(Channel channel, Message message) throws IOException {
        //判断库存
        String idString = new String(message.getBody(), "utf-8");
        String userId = idString.substring(idString.indexOf(":")+1);
        String couponId = idString.substring(0,idString.indexOf(":"));
        String key="hospital:coupon:"+couponId;
        int stock = redisTemplate.opsForValue().get(key);
        if(stock>0){
            //如果有库存，删减redis 库存
            redisTemplate.opsForValue().set(key,--stock);
            //加入数据库消息队列
            sqlProducer.send(idString);
            //手动确认消费消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            //将结果返回给用户
            Session session = WebSocketUtil.MESSAGEMAP.get(userId);
            WebSocketUtil.sendMessage(session,"恭喜您，抢到券了！");
        }else {
            //如果没库存，拒绝消息，成为死信
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }
    }
}